/*
 * Copyright (c) 2009. Silenus Consultoria, S.L.U.
 */
package es.silenus.detecta.task;

import mondrian.olap.CacheControl;
import mondrian.olap.Cube;

import mondrian.rolap.RolapSchema;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;

import java.util.Iterator;

import javax.sql.DataSource;


/**
 * Analytics task.
 *
 * @author <a href="mailto:malonso@silenus-consultoria.es">Mariano Alonso</a>
 *
 * @since 21-ago-2009 14:24:24
 */
public class AnalyticsTask extends AbstractTask {
	/**
	 * The Constant LOG.
	 */
	private static final Log LOG = LogFactory.getLog(AnalyticsTask.class);

	/**
	 * Template.
	 */
	private JdbcTemplate simpleJdbcTemplate;

	/**
	 * The analytics procedure name.
	 */
	private String analyticsProcedureName;

	/**
	 * Sets the data source.
	 *
	 * @param dataSource the data source.
	 */
	public void setDataSource(DataSource dataSource) {
		this.simpleJdbcTemplate = new JdbcTemplate(dataSource);
	}

	/**
	 * Sets the analytics procedure name.
	 *
	 * @param analyticsProcedureName the analytics procedure name.
	 */
	public void setAnalyticsProcedureName(final String analyticsProcedureName) {
		this.analyticsProcedureName = analyticsProcedureName;
	}

	/**
	 * Process analytics.
	 */
	private void processAnalytics() {
		LOG.info("Started analytics processing...");

		// Perform database archive
		SimpleJdbcCall archiveProcedure = new SimpleJdbcCall(simpleJdbcTemplate);

		archiveProcedure.withProcedureName(analyticsProcedureName).withoutProcedureColumnMetaDataAccess();
		archiveProcedure.execute();

		LOG.info("Finished survey lifecycle transition.");
	}

	/**
	 * Clears mondrian cache.
	 */
	private void clearMondrianCache() {
		LOG.info("Clearing mondrian cache...");


		// Clear mondrian cache
		Iterator<RolapSchema> schemaIt = RolapSchema.getRolapSchemas();
		CacheControl cacheControl = null;
		RolapSchema schema;

		while(schemaIt.hasNext()) {
			schema = schemaIt.next();
			cacheControl = schema.getInternalConnection().getCacheControl(null);

			for(Cube cube : schema.getCubes()) {
				cacheControl.flush(cacheControl.createMeasuresRegion(cube));
			}
		}

		if(cacheControl != null) {
			cacheControl.flushSchemaCache();
		}

		LOG.info("Mondrian cache cleared");
	}

	/**
	 * The execute method.
	 */
	protected void executeInternal() {
		// Process analytics
		processAnalytics();

		// Clear mondrian cache
		clearMondrianCache();
	}
}
